
#include "dbusManager.h"

dBusManager::dBusManager()
{
    m_activated = true;
    m_alwaysBusy = false;
    m_batteryCharged = false;
    m_keyboardDown = false;
    m_batteryOnCharge = false;
    /* Input events dbus interface */
    m_db_input = new QDBusInterface("org.freesmartphone.odeviced", "/org/freesmartphone/Device/Input",
                             "org.freesmartphone.Device.Input", QDBusConnection::systemBus(), this);

        if (!m_db_input->isValid())
        {
            fprintf(stderr, "[dBusManager::dBusManager] : %s\n", qPrintable(QDBusConnection::systemBus().lastError().message()));
        }

    /* Idle state dbus interface */
    m_db_state = new QDBusInterface("org.freesmartphone.odeviced", "/org/freesmartphone/Device/IdleNotifier/0",
                             "org.freesmartphone.Device.IdleNotifier",QDBusConnection::systemBus(), this);

        if (!m_db_state->isValid())
        {
            fprintf(stderr, "[dBusManager::dBusManager] : %s\n", qPrintable(QDBusConnection::systemBus().lastError().message()));
        }

    /* Power state dbus interface */
    m_db_power = new QDBusInterface("org.freesmartphone.odeviced","/org/freesmartphone/Device/PowerSupply/battery",
                             "org.freesmartphone.Device.PowerSupply",QDBusConnection::systemBus(),this);

        if (!m_db_power->isValid())
        {
            fprintf(stderr, "[dBusManager::dBusManager] : %s\n", qPrintable(QDBusConnection::systemBus().lastError().message()));
        }

    /* Connection dbus signals to locals slots */
    connect(m_db_input, SIGNAL(Event(QString,QString,int)),this, SLOT(buttonPressed(QString,QString,int)));
    connect(m_db_state, SIGNAL(State(QString)),this,SLOT(statusChanged(QString)));
    connect(m_db_power, SIGNAL(Capacity(int)),this,SLOT(capacityChanged(int)));
    connect(m_db_power, SIGNAL(PowerStatus(QString)),this,SLOT(powerStatusChanged(QString)));

    /* DBus server to export locals slots */
    QDBusConnection dbusManagerServer = QDBusConnection::sessionBus();
    if (!dbusManagerServer.registerService("org.neoManager.dbusConnection"))
        qDebug ("Error registering dbus connection");
    if (!dbusManagerServer.registerObject("/dbusManager", this, QDBusConnection::ExportAllSlots))
        qDebug("Error registering object on session bus");
}


/* Reactions to dbus events */

    // Buttons pressed
void dBusManager::buttonPressed(QString name,QString action,int seconde)
{
    if ( name == "AUX" && action == "released" )
    {
        if ( seconde < 1 && m_activated) //keyboard show
        {
            qDebug("[dBusManager::buttonPressed] : Aux button pressed");
            QDBusMessage msg = QDBusMessage::createSignal("/", "com.opendesk.buttons", "aux");
            msg << true;
            QDBusConnection::sessionBus().send(msg);
            if (m_keyboardDown) {
                QDBusMessage KBmsg = QDBusMessage::createSignal("/", "com.opendesk.keyboard", "show");
                KBmsg << 0;
                QDBusConnection::sessionBus().send(KBmsg);
            }
            else {
                QDBusMessage KBmsg = QDBusMessage::createSignal("/", "com.opendesk.keyboard", "hide");
                QDBusConnection::sessionBus().send(KBmsg);
            }
        }
        else //apps list
        {
            qDebug("[dBusManager::buttonPressed] : Aux button long time pressed");
            QDBusMessage msg = QDBusMessage::createSignal("/", "com.opendesk.buttons", "aux");
            msg << false;
            QDBusConnection::sessionBus().send(msg);
        }
    }
    else if ( name == "POWER" && action == "released" && m_activated )
    {
        if ( seconde < 1 ) // Shutdown and hibernate dialog
        {
            qDebug ("[dBusManager::buttonPressed] : Power button pressed");
            QDBusMessage msg = QDBusMessage::createSignal("/", "com.opendesk.buttons", "power");
            msg << true;
            QDBusConnection::sessionBus().send(msg);
        }
        else // Show power menu
        {
            qDebug("[dBusManager::buttonPressed] : Power button long time pressed");
            QDBusMessage msg = QDBusMessage::createSignal("/", "com.opendesk.buttons", "power");
            msg << false;
            QDBusConnection::sessionBus().send(msg);
        }

    }
}

    // Powers changements
void dBusManager::statusChanged(QString status )
{
    qDebug () << "[dBusManager::statusChanged] : Status changed : " << status;
    if ( m_activated )
    {
        if ( status == "idle" && m_alwaysBusy)
        {
            QDBusConnection dbus = QDBusConnection::systemBus();
            QDBusInterface m_db_usage ("org.freesmartphone.odeviced", "/org/freesmartphone/Device/IdleNotifier/0", "org.freesmartphone.Device.IdleNotifier", dbus);
            m_db_usage.call("SetState", "busy");
        }
        if ( status == "idle_dim" )
            emit idle();
    }
}

void dBusManager::capacityChanged(int capacity)
{
    qDebug () << "[dbusManager::capacityChanged] : Capacity changed : " << capacity;
    QDBusMessage msg = QDBusMessage::createSignal("/", "com.opendesk.notify", "battery");
    msg << m_batteryOnCharge<<capacity;
    QDBusConnection::sessionBus().send(msg);
}

void dBusManager::powerStatusChanged(QString powerStatus)
{
    if (m_activated)
    {
        qDebug() << "[dbusManager::powerStatusChanged] : power status changed to " << powerStatus;

        QString message;

        if ( powerStatus == "charging" ) {
            m_batteryOnCharge = true;
        }
        else if ( powerStatus == "discharging" )
        {
            m_batteryOnCharge = false;
            message = "Charger removed";
        }
        else if ( powerStatus == "full" )
        {
            m_batteryCharged = true;
            message = "Battery charged";
        }
        else if ( powerStatus == "empty" )
            message = "Battery empty";
        else if ( powerStatus == "critical" )
            message = "Battery is in critical state, please recharge";

        else
        {
            message = "Power status changed : ";
            message.append(powerStatus);
        }

        if ( ! m_batteryCharged )
            emit showMessage(message);
    }
}

    // Power management
void dBusManager::setAlwaysBusy(bool always)
{
    qDebug("[dBusManager::setAlwaysBusy] : changing busy mode");
    m_alwaysBusy = always;
}

bool dBusManager::isAlwaysBusy()
{
    return m_alwaysBusy;
}


/* Activation/Deactivation of dbus events */

void dBusManager::activate()
{
    m_activated = true;
}

void dBusManager::desactivate()
{
    m_activated = false;
}
